//
//  PredictionLogger.m
//  Pennyworth
//
//  Created by Chris Karr on 1/26/08.
//  Copyright 2008 Chris J. Karr. All rights reserved.
//

#import "PredictionLogger.h"
#import "LogManager.h"
#import "Learner.h"

#define LOG_PATH [NSString stringWithFormat:@"%@/Library/Application Support/Pennyworth/Logs/Predictions.log", NSHomeDirectory ()]
#define LOGS @"Prediction Log"
#define DATE_FORMAT @"yyyy-MM-dd"

@implementation PredictionLogger

@synthesize predictionList;
@synthesize predictions;

-(void) load
{
	NSFileManager * fm = [NSFileManager defaultManager];
	BOOL isDir = NO;
	
	[fm fileExistsAtPath:[LOG_PATH stringByDeletingLastPathComponent] isDirectory:&isDir];

	if (!isDir)
		[fm createDirectoryAtPath:[LOG_PATH stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];

	if ([fm fileExistsAtPath:LOG_PATH isDirectory:&isDir])
	{
		NSData * data = [NSData dataWithContentsOfFile:LOG_PATH];
		NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
			
		self.predictionList = [NSMutableArray arrayWithArray:[unarchiver decodeObjectForKey:LOGS]];
			
		[unarchiver release];
	}
	else
		self.predictionList = [NSMutableArray array];
}

- (void) awakeFromNib
{
	[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
	formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:DATE_FORMAT];

	[self load];

	self.predictions = [NSMutableDictionary dictionary];

	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processPrediction:) name:PREDICTION_FETCHED object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save:) name:LOG_PREDICTIONS object:nil];
}

- (void) processPrediction:(NSNotification *) note
{
	NSDictionary * userInfo = [note userInfo];

	NSString * key = [userInfo valueForKey:KEY];
	NSObject * value = [userInfo valueForKey:PREDICTION];

	if (key == nil || value == nil)
		return;
		
	[self.predictions setValue:value forKey:key];
}

- (void) save:(NSNotification *) note
{
	if (![[NSUserDefaults standardUserDefaults] boolForKey:ENABLE_LOGGING])
		return;

	[self.predictions setValue:[NSDate date] forKey:LOG_DATE];
	
	NSArray * predictionsCopy = [self.predictions copy];
	
	[self.predictionList addObject:predictionsCopy];
	
	[predictionsCopy release];
	
	NSMutableData * data = [NSMutableData data];
	
	NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
	[archiver encodeObject:self.predictionList forKey:LOGS];
	[archiver finishEncoding];

	[data writeToFile:LOG_PATH atomically:YES];
	[archiver release];
}

@end
